package com.mybatis.demo;

import com.mybatis.demo.domain.User;
import com.mybatis.demo.mapper.UserMapper;
import com.mybatis.demo.mapper.UserMapper2;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;

/**
 * @author ZhuYouBin
 * @version 1.0.0
 * @Date: 2022/9/1 16:23
 * @Description
 */
public class DemoTest {
    public static void main(String[] args) throws IOException {
        // 1、加载配置文件
        InputStream is = Resources.getResourceAsStream("mybatis-config.xml");
        // 2、创建 SqlSessionFactoryBuilder 对象
        SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
        // 3、创建 SqlSessionFactory 对象
        SqlSessionFactory sqlSessionFactory = builder.build(is);
        // 4、创建 SqlSession 对象
        // 5、获取 UserMapper
        // 执行操作
        User user = new User();
        user.setUsername("测试二级缓存");

        // 第一次查询
        SqlSession sqlSession = sqlSessionFactory.openSession();
        UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
        List<User> query = userMapper.query(user);
        System.out.println("第一次查询打印结果: ");
        query.forEach(System.out::println);
        // 关闭 SqlSession
        sqlSession.close();
        // 修改查询出来的缓存数据: 注意一定要在close() 之后修改，这样才能够修改二级缓存中的数据
        for (User user1 : query) {
            // 修改缓存数据
            user1.setUsername("csdn");
        }

        // 第二次读取数据
        SqlSession sqlSession2 = sqlSessionFactory.openSession();
        UserMapper userMapper2 = sqlSession2.getMapper(UserMapper.class);
        List<User> query2 = userMapper2.query(user);
        System.out.println("第二次查询打印结果: ");
        query2.forEach(System.out::println);
        // 关闭 SqlSession
        sqlSession2.close();

        // 关闭流
        is.close();
    }
}
